// topicarticle.go
package main

import (
	"fmt"

	"github.com/PuerkitoBio/goquery"
	log "github.com/alecthomas/log4go"
)

type TopicArticle struct {
	topicId  int
	nameMap  map[string]int
	err      error
	postFunc func(out *TopicArticle)
}

func CreateTopicArticle(topicId int, postFunc func(*TopicArticle)) *TopicArticle {
	ret := &TopicArticle{}
	ret.topicId = topicId
	ret.postFunc = postFunc
	return ret
}

func (self *TopicArticle) run() {
	url := fmt.Sprintf("https://bbs.hupu.com/%d.html", self.topicId)
	doc, err := goquery.NewDocument(url)
	if err != nil {
		log.Error("Cannot query artical url:%s, %v", url, err)
		self.err = err
		return
	} else {
		log.Trace("Fetched url: %s", url)
	}

	artTitle := doc.Find(".bbs_head .bbs-hd-h1 h1").Text()
	log.Info("%d: %s", self.topicId, artTitle)

	artContent := doc.Find(".quote-content").Text()
	log.Trace("%s", artContent)

	self.nameMap = gHupuSego.getNames(artTitle + artContent)
}

func (self *TopicArticle) post() {
	if self.err == nil && self.postFunc != nil {
		self.postFunc(self)
	}
}

func (self *TopicArticle) Merge(merged map[string]int) {
	for name, count := range self.nameMap {
		merged[name] += count
	}
}
